/*
 * Copyright © 2010 SenseForce.com.
 * The Software shall be used for Good, not Evil.
 */

package com.senseforce.classes;

import com.senseforce.midlets.StartSocket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;

/**
 *
 * @author jcccn
 * @site http://www.senseforce.com/
 */
public class Server implements Runnable, CommandListener {
    private StartSocket parent;
    private Display display;
    private Form f;
    private StringItem si;
    private TextField tf;
    private boolean stop;
    private Command sendC = new Command("Send", Command.ITEM, 1);
    private Command exitC = new Command("Exit", Command.ITEM, 1);
    InputStream is;
    OutputStream os;
    SocketConnection sc;
    ServerSocketConnection ssc;
    Sender sender;

    public Server(StartSocket midlet) {
        parent = midlet;
        display = Display.getDisplay(parent);
        f = new Form("Socket Server");
        si = new StringItem("Status:","");
        tf = new TextField("Send:", "", 30, TextField.ANY);
        f.append(si);
        f.append(tf);
        f.addCommand(exitC);
        f.setCommandListener(this);
        display.setCurrent(f);
    }

    public void start(){
        Thread t = new Thread(this);
        t.start();
    }

    public void run() {
        try {
            si.setText("Waiting for client connecting...");
            ssc = (ServerSocketConnection)Connector.open("socket://:50009");
            sc = (SocketConnection)ssc.acceptAndOpen();
            si.setText("Connection accepted");
            is = sc.openInputStream();
            os = sc.openOutputStream();
            sender = new Sender(os);
            f.addCommand(sendC);
            while(true) {
                StringBuffer sb = new StringBuffer();
                int c = 0;
                while(((c = is.read())!='\n') && (c!=-1)) {
                    sb.append((char)c);
                }
                if (c == -1) {
                    break;
                }
                si.setText("Accepted msg:" + sb.toString());
            }
            stop();
            si.setText("Connection closed.");
            f.removeCommand(sendC);
        } catch (IOException e) {
            if (e.getMessage().equals("ServerSocket Open")) {
                Alert alert = new Alert("Server", "Port 50009 may be seated.", null, AlertType.ERROR);
                alert.setTimeout(Alert.FOREVER);
                alert.setCommandListener(this);
                display.setCurrent(alert);
            }
            else {
                if (!stop) {
                    System.err.println(e);
                }
            }
        }
    }

    public void commandAction(Command c, Displayable d) {
        if ((c == sendC) && (!parent.isPaused())) {
            sender.send(tf.getString());
        }
        if ((c == Alert.DISMISS_COMMAND) || (c == exitC)) {
            parent.notifyDestroyed();
            parent.destroyApp(true);
        }
    }

    public void stop() {
        try {
            stop = true;
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
            if (sc != null) {
                sc.close();
            }
            if (ssc != null) {
                ssc.close();
            }
        } catch (IOException e) {

        }
    }

}
